package com.qiezikaka.kaka.ui.detail;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.SizeUtils;
import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qiezikaka.kaka.R;
import com.qiezikaka.kaka.adapter.DialogBackAdapter;
import com.qiezikaka.kaka.base.BaseActivity;
import com.qiezikaka.kaka.bean.QcodeInfo;
import com.qiezikaka.kaka.bean.SiteDetailInfo;
import com.qiezikaka.kaka.bean.SiteSceneShowInfo;
import com.qiezikaka.kaka.bean.UploadImgInfo;
import com.qiezikaka.kaka.databinding.ActivityTakleCameraFaceDetailBinding;
import com.qiezikaka.kaka.http.HttpClient;
import com.qiezikaka.kaka.view.CircleViewOutlineProvider;
import com.qiezikaka.kaka.view.GPUImageMirrorFilter;
import com.qiezikaka.kaka.view.v1.GPUImageBeautyFilter;
import com.qiezikaka.kaka.view.v1.Util;
import com.stx.xhb.androidx.XBanner;
import com.yzq.zxinglibrary.encode.CodeCreator;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import jp.co.cyberagent.android.gpuimage.GPUImage;
import jp.co.cyberagent.android.gpuimage.GPUImageFilterGroup;

public class DetailCameraFaceTakle03Activity extends BaseActivity<DetailPresenter> implements DetailContract.View, View.OnClickListener {
    private ActivityTakleCameraFaceDetailBinding detailBinding;
    private DetailPresenter presenter;
    private String pid;
    private String[] mPermissions = {Manifest.permission.CAMERA};
    private static final int PERMISSION_REQUEST_CODE = 10;
    private boolean hasPermissions;
    private boolean resume = false;//解决home键黑屏问题
    private File uploadFile;
    private boolean isPreviewing;
    private int currentCameraId;
    private GPUImage gpuImage;
    private GPUImageFilterGroup magicFilterGroup;
    private GPUImageFilterGroup noMagicFilterGroup;
    private Camera camera;
    private static final int PICTURE_WIDTH = 1280;
    private static final int PICTURE_HEIGHT = 720;
    private static final int PREVIEW_WIDTH = 1280;
    private static final int PREVIEW_HEIGHT = 720;
    private String price = "0";
    private String thumbStr;
    private List<SiteSceneShowInfo.DataBean> beanList;
    private String androidId;

    @Override
    public View getLayout() {
        detailBinding = ActivityTakleCameraFaceDetailBinding.inflate(getLayoutInflater());
        return detailBinding.getRoot();
    }

    @Override
    protected DetailPresenter getPresenter() {
        if (presenter == null) {
            presenter = new DetailPresenter(this, this);
        }
        return presenter;
    }

    @Override
    protected void initEventAndData() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        Intent intent = getIntent();
        pid = intent.getStringExtra("pid");
        presenter.getSiteSceneShow(pid);
        initview();
        initTakleCamera();
    }

    private void initview() {
        detailBinding.glsvMain.setOutlineProvider(new CircleViewOutlineProvider(50));
        detailBinding.glsvMain.setClipToOutline(true);
        detailBinding.ivBtnTable.setOnClickListener(this::onClick);
        detailBinding.ivBtnFace.setOnClickListener(this::onClick);
        detailBinding.ivBack.setOnClickListener(this::onClick);
        detailBinding.ivBtnUpload.setOnClickListener(this::onClick);
        detailBinding.ivBtnChongPai.setOnClickListener(this::onClick);


    }

    public static boolean isDestroy(Activity mActivity) {
        if (mActivity == null || mActivity.isFinishing() || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())) {
            return true;
        } else {
            return false;
        }
    }

    private void initTakleCamera() {
        //权限检查
        if (Util.checkPermissionAllGranted(this, mPermissions)) {
            hasPermissions = true;
        } else {
            ActivityCompat.requestPermissions(this, mPermissions, PERMISSION_REQUEST_CODE);
        }
        isPreviewing = false;
        currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;  //CAMERA_FACING_BACK
//        currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
        gpuImage = new GPUImage(this);
        gpuImage.setGLSurfaceView(detailBinding.glsvMain);
        magicFilterGroup = new GPUImageFilterGroup();
        magicFilterGroup.addFilter(new GPUImageBeautyFilter()); //GPUImageBeautyFilter
        noMagicFilterGroup = new GPUImageFilterGroup();
        noMagicFilterGroup.addFilter(new GPUImageMirrorFilter());
        gpuImage.setFilter(magicFilterGroup);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (hasPermissions) {
            startCamera(currentCameraId);
            resume = true;
        }
    }

    private void startCamera(int cameraId) {
        try {
            if (camera == null) {
                currentCameraId = cameraId;
                camera = Camera.open(cameraId);
                Camera.Parameters parameters = camera.getParameters();
                parameters.setPictureFormat(PixelFormat.JPEG);

                List<Camera.Size> sizeList = parameters.getSupportedPictureSizes();
                int width = 0;
                int height = 0;

                for (Camera.Size size : sizeList) {
                    if (size.width * size.height <= PICTURE_HEIGHT * PICTURE_WIDTH) {
                        if (size.width * size.height > width * height) {
                            width = size.width;
                            height = size.height;
                        }
                    }
                }
                parameters.setPictureSize(width, height);
                sizeList = parameters.getSupportedPreviewSizes();
                width = 0;
                height = 0;
                for (Camera.Size size : sizeList) {
                    if (size.width * size.height <= PREVIEW_WIDTH * PREVIEW_HEIGHT) {
                        if (size.width * size.height > width * height) {
                            width = size.width;
                            height = size.height;
                        }
                    }
                }
                parameters.setPreviewSize(width, height);
                List<String> stringList = parameters.getSupportedFocusModes();
                for (String s : stringList) {
//                    LogUtil.d(s);
                }
                if (cameraId == 0) {
                    if (stringList.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                    }
                }
                try {
                    camera.setParameters(parameters);
                } catch (RuntimeException e) {
                    Log.e("可见", "Failed to set parameters", e);
                }

                if (!isPreviewing) {
                    isPreviewing = true;
                    gpuImage.setUpCamera(camera, cameraId == 0 ? 0 : 180, cameraId > 0, false);
                }
            }
        } catch (Exception e) {
            showToast("错误" + e.getMessage());
        }
    }


    private void uploadUI(File files) {
        androidId = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        // 准备表单参数
        Map<String, String> params = new HashMap<>();
        params.put("back", thumbStr);//thumb
        params.put("price", price);
        params.put("id", pid);
        params.put("address", androidId);
        HttpClient.post01("http://api.datang.qzkaka.com/v1/public/qr-img", params, files, "image/jpeg", QcodeInfo.class, new HttpClient.HttpResponseCallback<QcodeInfo>() {
            @Override
            public void onSuccess(QcodeInfo info) {
                mTipDialog.dismiss();
                if (info.getCode() == 200) {
                    detailBinding.ivBtnTable.setVisibility(View.GONE);
                    detailBinding.ivBtnUpload.setVisibility(View.GONE);
                    detailBinding.ivBtnChongPai.setVisibility(View.GONE);
                    detailBinding.ivXuniKuan.setVisibility(View.GONE);
                    QcodeInfo.DataBean infoData = info.getData();
//                    qCodeDialog(infoData);
                    // 释放资源
                    clearCamera();
                } else if (info.getCode() == 422) {
                    showToast(info.getMsg());
                    detailBinding.ivBtnTable.setVisibility(View.VISIBLE);
                    detailBinding.ivBtnChongPai.setVisibility(View.GONE);
                    detailBinding.ivBtnUpload.setVisibility(View.GONE);
                    clearCamera();
                    startCamera(currentCameraId);

                }
            }

            @Override
            public void onFailure(String error) {
//                showToast("上传成功");
                detailBinding.ivBtnTable.setVisibility(View.VISIBLE);
                detailBinding.ivBtnChongPai.setVisibility(View.GONE);
            }
        });
    }

    private boolean isFace = true;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_btn_table:
//                showToast("拍照");
                detailBinding.ivBtnTable.setVisibility(View.GONE);
                camera.takePicture(null, null, new Camera.PictureCallback() {
                    @Override
                    public void onPictureTaken(byte[] data, Camera camera) {
                        Bitmap bitmap = rotateBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), 0);
                        detailBinding.ivBtnUpload.setVisibility(View.VISIBLE);
                        detailBinding.ivBtnChongPai.setVisibility(View.VISIBLE);


                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();

                        int xq = width/2 - SizeUtils.dp2px(150);
                        int yq = SizeUtils.dp2px(16);

                        int xh = SizeUtils.dp2px(350);
                        int yh = SizeUtils.dp2px(350);

//                        Bitmap bitmap1 = Bitmap.createBitmap(bitmap, width / 2, 0, width / 3, height);
                        Bitmap bitmap1 = Bitmap.createBitmap(bitmap, xq, yq, xh, yh);
                        try {
                            uploadFile = saveFile(bitmap1, "pic");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });

                break;
            case R.id.iv_btn_chong_pai:
                // 重拍
                detailBinding.ivBtnTable.setVisibility(View.VISIBLE);
                detailBinding.ivBtnChongPai.setVisibility(View.GONE);
                detailBinding.ivBtnUpload.setVisibility(View.GONE);
                clearCamera();
                startCamera(currentCameraId);
                break;
            case R.id.iv_btn_upload://上传
                mTipDialog.show();
                uploadUI(uploadFile);
//                mTipDialog.show();
//                uploadUI01(uploadFile);
                break;
//            case R.id.btn_face:
//                isFace = !isFace;
//                gpuImage.setFilter(isFace ? magicFilterGroup : noMagicFilterGroup);
//                break;

        }
    }

    public File saveFile(Bitmap bm, String fileName) throws IOException {//将Bitmap类型的图片转化成file类型，便于上传到服务器
//        String path = getExternalFilesDir(null) + "/pic.jpg";
        String path = getExternalFilesDir(null).getAbsolutePath();
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path, fileName);//+ fileName
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
        return myCaptureFile;

    }

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm     需要旋转的图片
     * @param degree 旋转角度
     * @return 旋转后的图片
     */
    private Bitmap rotateBitmap(Bitmap bm, int degree) {
        Bitmap returnBm = null;
        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    // 设置按钮样式1
    private void setButtonStyle1(View view) {
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.bg_tp_kuan); // 获取样式作为Drawable对象
        view.setBackground(drawable);
    }

    private void setButtonStyle2(View view) {
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.bg_tp_kuan_normal); // 获取样式作为Drawable对象
        view.setBackground(drawable);
    }

    @Override
    public void onFailer(Throwable throwable) {

    }

    @Override
    public void onSiteDetail(SiteDetailInfo info) {

    }

    @Override
    public void onUpload(UploadImgInfo info) {
        switch (info.getStatus()) {
            case 200:
                UploadImgInfo.DataBean infoData = info.getData();
                if (infoData != null) {
                    String thumb = infoData.getThumb();
                    showToast(thumb);
                }
                break;
            case 422:
                showToast(info.getMessage());
                break;
        }
    }

    /**
     * 风格背景图
     *
     * @param info
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onSiteSceneShow(SiteSceneShowInfo info) {
        switch (info.getStatus()) {
            case 200:
                price = info.getPrice();
                beanList = info.getData();
                // 以逗号拼接
                thumbStr = beanList.stream()
                        .map(SiteSceneShowInfo.DataBean::getThumb)  // 提取thumb字段
                        .collect(Collectors.joining(","));
                Log.e("拼接结果", thumbStr);

                if (!beanList.isEmpty()) {
                    SiteSceneShowInfo.DataBean dataBean = beanList.get(0);
                    if (dataBean != null) {
                        loadImageIntoImageView(detailBinding.rivImageYu, dataBean.getThumb());
                    }
                }
                break;
            case 422:
                showToast(info.getMessage());
                break;
        }
    }

    private void loadImageIntoImageView(ImageView imageView, String imageUrl) {
        if (!isDestroy(DetailCameraFaceTakle03Activity.this)) {
            Glide.with(this)
                    .load(imageUrl)
                    .into(imageView);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        clearCamera();
    }

    private void clearCamera() {
        if (camera != null) {
            gpuImage.deleteImage();
            camera.setPreviewCallback(null);
            camera.stopPreview();
            isPreviewing = false;
            camera.release();
            camera = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearCamera();
    }

    /**
     * 申请权限结果返回处理
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean isAllGranted = true;
            for (int grant : grantResults) {  // 判断是否所有的权限都已经授予了
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }
            if (isAllGranted) { // 所有的权限都授予了
                startCamera(currentCameraId);
            } else {// 提示需要权限的原因
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("拍照需要允许权限, 是否再次开启?")
                        .setTitle("提示")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(DetailCameraFaceTakle03Activity.this, mPermissions, PERMISSION_REQUEST_CODE);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        });
                builder.create().show();
            }
        }
    }


}
